package com.zzg.datasource.config;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import com.alibaba.druid.pool.xa.DruidXADataSource;
import com.atomikos.jdbc.AtomikosDataSourceBean;
import com.zzg.datasource.properties.MySQLSlave;

@Configuration
@MapperScan(basePackages = { "com.zzg.mapper.slave" }, sqlSessionTemplateRef = "sqlSessionTemplateSlave")
public class MySQLSlaveConfig {
	@Bean(name = "dataSourceSlave")
	public DataSource getDataSourceSlave(MySQLSlave slave) {
		DruidXADataSource dataSource = new DruidXADataSource();
		BeanUtils.copyProperties(slave, dataSource);
		AtomikosDataSourceBean xaDataSource = new AtomikosDataSourceBean();
		xaDataSource.setXaDataSource(dataSource);
		xaDataSource.setUniqueResourceName("dataSourceSlave");
		return xaDataSource;
//		return new AtomikosDataSourceBean();
	}
	
	@Bean(name = "sqlSessionFactorySlave")
	public SqlSessionFactory sqlSessionFactorySlave(@Qualifier("dataSourceSlave") DataSource dataSource)
			throws Exception {
		SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
		bean.setDataSource(dataSource);
		bean.setMapperLocations(
				new PathMatchingResourcePatternResolver().getResources("classpath:/mapper/slave/*.xml"));
		return bean.getObject();
	}
	
	@Bean(name = "sqlSessionTemplateSlave")
	public SqlSessionTemplate sqlSessionTemplateCarInfo(
			@Qualifier("sqlSessionFactorySlave") SqlSessionFactory sqlSessionFactory) throws Exception {
		return new SqlSessionTemplate(sqlSessionFactory);
	}
}
